package com.lh.ssm.service.impl;

import com.lh.ssm.domain.Cart;
import com.lh.ssm.domain.Product;
import com.lh.ssm.mapper.CartMapper;
import com.lh.ssm.mapper.ProductMapper;
import com.lh.ssm.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public int createCart(int pid, int uid) {

        Cart cart = cartMapper.findCart(pid, uid);
        Product product = productMapper.findProductById(String.valueOf(pid));
        System.out.println(cart);
        System.out.println(product);
        if (cart != null) {
            Cart cart1 = new Cart(null, uid, pid, null, cart.getTotal().add(product.getPrice()), (cart.getCount() + 1));
            return cartMapper.updateCart(cart1);
            //return cartMapper.updateCart(cart.getTotal().add(product.getPrice()), (int)(cart.getCount() + 1),pid, uid );
        } else {
            int i = cartMapper.insertCart(uid, pid, product.getPrice(), 1);
            return i;
        }
    }

    @Override
    public List<Cart> findAllByUid(int uid) {
        return cartMapper.findAllCart(uid);
    }

    @Override
    public int updateCartById(int cid, int cnum, BigDecimal price) {

        //先将需要做操作的那一行购物车信息找出来
        Cart cart = cartMapper.getCartByCid(cid);
        System.out.println(cart);

        if (cnum > cart.getCount()) {
            BigDecimal total = cart.getTotal().add(price);
            return cartMapper.updateCartByTotal(cid, cnum, total);
        } else {
            BigDecimal total = cart.getTotal().subtract(price);
            return cartMapper.updateCartByTotal(cid, cnum, total);
        }
    }

    @Override
    public int deleteCartById(int cid) {
        return cartMapper.deleteById(cid);

    }

    @Override
    public int clearCart(int uid) {
        return cartMapper.deleteByUid(uid);
    }

    @Override
    public List<Cart> showCartByUid(int uid) {
        List<Cart> carts = cartMapper.selectCartByUid(uid);
        System.out.println(carts);
        return carts;
    }


}
